package ext.acae2.baseline.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import wt.doc.WTDocument;
import wt.epm.EPMDocument;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTProperties;
import wt.vc.baseline.ManagedBaseline;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignedActivity;
import ext.acae2.ACAEConstants;
import ext.acae2.baseline.BaselineConstants;
import ext.acae2.util.IBAUtil;
import ext.acae2.workflow.WorkflowHelper;

public class BaselineCreDocXLS {
	
	private static final Logger LOGGER = LogR.getLogger(BaselineCreDocXLS.class
			.getName());

	private class Column {
		public static final short A = 0;
		public static final short B = 1;
		public static final short C = 2;
		public static final short D = 3;
	}
	
    public static String WT_HOME = "";
	
	static {
		
		try {
			WTProperties wtproperties = WTProperties.getLocalProperties();
			WT_HOME = wtproperties.getProperty("wt.home");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
	public static String getFilePath(String... params) {
		String rsString = "";
		StringBuffer sb = new StringBuffer();
		if (!(params == null || params.length == 0)) {
			for (String param : params) {
				sb.append(param).append(File.separator);
			}
			rsString = sb.substring(0, sb.length()-1);
		}
		LOGGER.debug(rsString);
		return rsString;
	}
	
    /**
	 * 产生基线信息报表
	 * @param mb
	 * @return
	 * @throws Exception
	 */
	public static String generateBaselineCreXLS(ManagedBaseline mb) throws Exception {
		LOGGER.debug("3");
		
		String filePath = "";
		File templateFile = new File(getFilePath(WT_HOME, "codebase", "ext", "acae2", "conf", "BaselineInfo_Template.xls"));
		if (templateFile != null && templateFile.exists()) {
			// copy file
			InputStream template_is = new FileInputStream(templateFile);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
			TimeZone china =TimeZone.getTimeZone("Asia/Shanghai");        
			sf.setTimeZone(china);
			Timestamp ts_now = new Timestamp(System.currentTimeMillis());
			
			filePath = getFilePath(WT_HOME, "temp", "基线信息报表-" + sf.format(ts_now) + ".xls");
			File out_file = new File(filePath);
			LOGGER.debug(filePath);
			LOGGER.debug(out_file.getAbsolutePath());
			boolean canCreate = false;
			if (!out_file.exists()) {
				canCreate = out_file.createNewFile();
				LOGGER.debug("!out_file.exists()");
			} else {
				out_file.delete();
				canCreate = out_file.createNewFile();
				LOGGER.debug("out_file.exists()");
			}
			LOGGER.debug("canCreate: " + canCreate);
			if(canCreate) {
				LOGGER.debug("template_os");
				OutputStream template_os = new FileOutputStream(out_file);
				byte[] buffer = new byte[255];
				int count = -1;
				while ((count = template_is.read(buffer)) > -1) {
					template_os.write(buffer, 0, count);
				}
				template_os.close();
			}
			template_is.close();
			template_is = null;
			if (canCreate) {
				LOGGER.debug("writeBaselineInfoReport");
				InputStream wb_in = new FileInputStream(out_file);
				HSSFWorkbook wb = new HSSFWorkbook(wb_in);
				writeBaselineInfoReport(wb, mb);
				OutputStream wb_os = new FileOutputStream(out_file);
				wb.write(wb_os);
				wb_in.close();
				wb_os.close();
			}
		}
		LOGGER.debug(filePath);
		return filePath;
	}
	
	/**
	 * 填写基线报表信息
	 * @param wb
	 * @param mb
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static void writeBaselineInfoReport(HSSFWorkbook wb, ManagedBaseline mb) throws Exception {
		HSSFSheet ws = wb.getSheetAt(0);
		
		String localMessage = TypedUtilityServiceHelper.service.getLocalizedTypeName(mb).getLocalizedMessage(Locale.CHINA);
		QueryResult processqr = WfEngineHelper.service.getAssociatedProcesses(mb, WfState.CLOSED_COMPLETED, mb.getContainerReference());
		List<WfActivity> activityList = new ArrayList<WfActivity>();
		if(processqr.hasMoreElements()){
			Object obj = processqr.nextElement();
			if(obj instanceof WfProcess){
				WfProcess process = (WfProcess)obj;
				activityList = WorkflowHelper.getActivities(process, activityList);
			}
		}
		
		String identifierstr = TypedUtilityServiceHelper.service.getExternalTypeIdentifier(mb).toString();
		String baselineType="";
		IBAUtil ibaUtil = new IBAUtil(mb);
		if(identifierstr.indexOf(BaselineConstants.TYPE_CONFIGBASELINE)>-1){
			baselineType = ibaUtil.getIBAValue(BaselineConstants.IBA_BASELINETYPE);
		}else if(identifierstr.indexOf(BaselineConstants.TYPE_PHASEBASELINE)>-1){
			baselineType = ibaUtil.getIBAValue(BaselineConstants.IBA_PHASETYPE);
		}
		if(StringUtils.isNotBlank(baselineType)){
			baselineType = baselineType.substring(baselineType.indexOf("-")+1);
		}
		String projectCode = ibaUtil.getIBAValue(BaselineConstants.IBA_PROJECTCODE);
		
		// 建立Style
		HSSFCellStyle seqCst = wb.createCellStyle();
		seqCst.setBorderTop(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderRight(HSSFCellStyle.BORDER_THIN);
		seqCst.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
		TimeZone china =TimeZone.getTimeZone("Asia/Shanghai");        
		sf.setTimeZone(china);
		Timestamp ts = new Timestamp(mb.getCreateTimestamp().getTime());
		String baselineTime = sf.format(ts);
		
		String baselineName = mb.getName();
		String baselineNumber = mb.getNumber();
		
		// 填写信息
		// 2
		int currentRow = 1;
		HSSFRow row = ws.getRow(currentRow);
		HSSFCell cell = row.getCell(Column.B);
		//cell.setCellValue("1");
		//cell = row.getCell(Column.B);
		cell.setCellValue(baselineType);
		cell = row.getCell(Column.D);
		cell.setCellValue(baselineTime);
		currentRow ++;
		
		// 4
		row = ws.getRow(currentRow);
		cell = row.getCell(Column.B);
		cell.setCellValue(baselineNumber);
		cell = row.getCell(Column.D);
		cell.setCellValue(baselineName);
		currentRow ++;
		
		
		if(activityList==null||activityList.size()==0){
			// 5
			row = ws.getRow(currentRow);
			cell = row.getCell(Column.B);
			cell.setCellValue("");
			cell = row.getCell(Column.D);
			cell.setCellValue("");
//			currentRow ++;

			// 7
			row = ws.getRow(currentRow+1);
			cell = row.getCell(Column.B);
			cell = row.getCell(Column.B);
			cell.setCellValue("");
		}else{
			for(WfActivity activity:activityList){
				WfAssignedActivity assignedActivity = (WfAssignedActivity)activity;
				List<WTUser> users = WorkflowHelper.getWorkItemCompleteBy(assignedActivity);
				StringBuffer completeUsername = new StringBuffer();
				for(WTUser user:users){
					completeUsername.append(user.getFullName());
					completeUsername.append(";");
				}
				if(activity.getName().equals(ACAEConstants.ACAE_BASELINE_BIANZHI_ACTIVITY_NAME)){
					row = ws.getRow(currentRow);
					cell = row.getCell(Column.B);
					cell.setCellValue(completeUsername.toString().substring(0,completeUsername.toString().length()-1));
				}else if(activity.getName().equals(ACAEConstants.ACAE_BASELINE_REVIEW_ACTIVITY_NAME)){
					row = ws.getRow(currentRow+1);
					cell = row.getCell(Column.B);
					cell.setCellValue(completeUsername.toString().substring(0,completeUsername.toString().length()-1));
				}else if(ACAEConstants.ACAE_BASELINE_SINGER_ACTIVITY_NAME.equals(activity.getName())){
					row = ws.getRow(currentRow);
					cell = row.getCell(Column.D);
					cell.setCellValue(completeUsername.toString().substring(0,completeUsername.toString().length()-1));
				}else if(ACAEConstants.ACAE_BASELINE_APPROVE_ACTIVITY_NAME.equals(activity.getName())){
					row = ws.getRow(currentRow+1);
					cell = row.getCell(Column.D);
					cell.setCellValue(completeUsername.toString().substring(0,completeUsername.toString().length()-1));
				}
			}
		}
		
		
		currentRow += 4;

		List<WTPart> baselineParts = new ArrayList<WTPart>();
		List<EPMDocument> baselineEpmDocs = new ArrayList<EPMDocument>();
		List<WTDocument> baselineDocs = new ArrayList<WTDocument>();

		BaselineUtil.getBaselineDocsAndParts(mb, baselineDocs, baselineParts, baselineEpmDocs);
		Collections.sort(baselineParts, ADFUtil.partNumComp);
		Collections.sort(baselineDocs, ADFUtil.docNumComp);
		Collections.sort(baselineEpmDocs, ADFUtil.epmDocNumComp);
		
        int seq = 1;
        
        for ( WTPart part : baselineParts ) {
            
            String number = part.getNumber();
            String version = part.getVersionIdentifier().getValue() + "." + part.getIterationIdentifier().getValue();
            String name = part.getName();
            
            row = ws.createRow(currentRow);
        	LOGGER.debug("part number:" + number);
        	LOGGER.debug("part version:" + version);
        	LOGGER.debug("part name:" + name);
        	LOGGER.debug("part getType:" + part.getType());
        	
        	cell = row.createCell(Column.A);
        	cell.setCellValue(String.valueOf(seq));
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.B);
        	cell.setCellValue(number);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.C);
        	cell.setCellValue(version);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.D);
        	cell.setCellValue(name);
        	cell.setCellStyle(seqCst);
        	
        	currentRow++;
        	seq++;
        }		
        
        for ( EPMDocument epmDoc : baselineEpmDocs ) {
            
            String number = epmDoc.getNumber();
            String version = epmDoc.getVersionIdentifier().getValue() + "." + epmDoc.getIterationIdentifier().getValue();
            String name = epmDoc.getName();
            
            row = ws.createRow(currentRow);
        	LOGGER.debug("epmDoc number:" + number);
        	LOGGER.debug("epmDoc version:" + version);
        	LOGGER.debug("epmDoc name:" + name);
        	
        	cell = row.createCell(Column.A);
        	cell.setCellValue(String.valueOf(seq));
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.B);
        	cell.setCellValue(number);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.C);
        	cell.setCellValue(version);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.D);
        	cell.setCellValue(name);
        	cell.setCellStyle(seqCst);
        	
        	currentRow++;
        	seq++;
        }		
        
        for (WTDocument doc : baselineDocs) {
        	
        	String number = doc.getNumber();
            String version = doc.getVersionIdentifier().getValue() + "." + doc.getIterationIdentifier().getValue();
            String name = doc.getName();
            
        	row = ws.createRow(currentRow);
        	LOGGER.debug("doc number:" + number);
        	LOGGER.debug("doc version:" + version);
        	LOGGER.debug("doc name:" + name);
        	
        	cell = row.createCell(Column.A);
        	cell.setCellValue(String.valueOf(seq));
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.B);
        	cell.setCellValue(number);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.C);
        	cell.setCellValue(version);
        	cell.setCellStyle(seqCst);
        	
        	cell = row.createCell(Column.D);
        	cell.setCellValue(name);
        	cell.setCellStyle(seqCst);
        	
        	currentRow++;
        	seq++;
        }
        
	}
	
}
